<template>
  <div id="app" class="skEvaluation">
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-row>
        <!-- <div v-if="evaluateModeNum == 0"> -->
        <a-col :span="24">
          <a-form-model-item label="评价维度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dimensionality" :rules="{ required: dimensionalityStatus, message: '请选择评价维度!' }">
            <a-select
              v-model="model.dimensionality"
              placeholder="请选择评价维度"
              mode="multiple"
              @select="getEvaluate"
              @deselect="deselectEvaluate"
            >
              <a-select-option v-for="item in evaluateList" :key="item.value" :value="item.value">{{
                item.title
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="24" v-if="model.studentDimensionEvaluationList.length > 0">
          <a-form-model-item
            label="评分"
            :colon="false"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          ></a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item
            v-for="item in model.studentDimensionEvaluationList"
            :key="item.dimensionCode"
            :label="item.dimensionName"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <sk-rate
              v-model="item.score"
              :rateTexts="rateTexts"
              :rateId="item.dimensionCode"
              checkedIcon="icon-huaqi"
              unCheckedIcon="icon-huaqi1"
              @starChange="onStarChange"
            ></sk-rate>
          </a-form-model-item>
        </a-col>
        <a-col :span="24" v-if="!disabled || model.evaluationContent">
          <a-form-model-item label="评语" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="evaluationContent">
            <a-textarea
              v-model="model.evaluationContent"
              placeholder="请输入评语"
              :auto-size="{ minRows: 3, maxRows: 6 }"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item>
            <div class="type-checkbox-box">
              <div v-for="(el) in evaluateTemList" :key="el.id" style="display: flex;flex-wrap: wrap;">
                <div class="type-checkbox-content" v-for="(item) in el.children" :key="item.value" @click.stop="setEvaluationContent(item)">
                  <div  :class="['type-label',selectType(item) && item.title !=notEvaluate?'type-label-active':'']" >{{item.title}}</div>
                </div>
              </div>
            </div>
          </a-form-model-item>
        </a-col>
        <!-- 无法查看放大图片，查看详情隐藏 -->
        <a-col :span="24" v-if="!disabled">
          <a-form-model-item
            label="照片"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            style="line-height: 0;"
          >
            <sk-upload ref="skUpload" accept="image/*" :evaluationData="evaluationData" :evaluationDataInfo="evaluationDataInfo" :selectDimensionalityStatus="selectDimensionalityStatus" :stuMultiple="false" :fileMultiple="true" @photoData="getPhotoData" :maxNumber="imgMaxNumber" v-bind="$attrs"></sk-upload>
            <div>最多上传 <span style="color: #f5222d;">{{ imgMaxNumber }}</span> 张照片</div>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import {  getAction,getFileAccessHttpUrl } from '@/api/manage'
import SkRate from './skRate.vue'
import SkUpload from "./skUpload.vue";
export default {
  name: 'skEvaluation',
  data() {
    return {
      imgMaxNumber:9,
      model: {
        evaluationContent: '',
        studentDimensionEvaluationList: []
      },
      photoData:null,
      rateTexts: ['继续努力', '一般', '不错', '很棒', '非常棒'], // 评分组件显示的提示语，可选
      evaluateList: [], //评价维度列表
      evaluateTemList: [], //评价模板列表
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {},
      studentPhoto:[],
      evaluateModeNum:0,
      dimensionalityStatus:null,
      selectDimensionalityStatus:false,
      notEvaluate:"暂无评价模板",
      evaluationContentValue:"",
      evaluationContentArr:[]
    }
  },
  props:{
    evaluationData:Object,
    evaluationDataInfo:Object,
    evaluationCategory:Number,
    disabled:Boolean
  },
  watch:{
    evaluationDataInfo:{
      handler(val){
        this.model = val;
        this.model.dimensionality = []
        val.studentDimensionEvaluationList.forEach(item => {
          this.model.dimensionality.push(item.dimensionCode)
        });
        // this.evaluateModeNum = val.evaluateModeNum
        // this.studentPhoto.push({
        //   id:val.studentId,
        //   name:"照片",
        //   photo:val.photo
        // })
        console.log(this.studentPhoto);
      }
    },
    "evaluationData.type":{
      handler(val){
        this.dimensionalityStatus = val == this.evaluationCategory?true:false
      },
      immediate:true
    }
  },
  components: {
    SkRate,
    SkUpload
  },

  computed: {
   
  },

  async created() {
    this.evaluateList = await this.getEvaluateList(false)
    console.log(this.evaluationData);
    
  },

  activated() {},

  mounted() {
  },

  methods: {
    // 获取所有维度
    getEvaluateList(async) {
      return new Promise((resolve, reject) => {
        const url = '/table/skCategory/loadTreeRoot'
        // async=true时只返回一级数据，false返回所有子节点数据
        const params = {
          async: async,
          pcode: 'A03'
        }
        getAction(url, params)
          .then(res => {
            if (res.success) {
              resolve(res.result)
            } else {
              this.$message.warning(res.message)
            }
          })
          .catch(error => {
            console.error(error)
          })
      })
    },
    // 获取选择的维度
    getEvaluate(e) {
      this.selectDimensionalityStatus = true
      let evaluateItem = this.evaluateList.find(item => item.value == e)
      this.model.studentDimensionEvaluationList.push({
        dimensionCode: evaluateItem.value,
        dimensionName: evaluateItem.title,
        score: 0
      })
    },
    
    // 删除选择的维度
    deselectEvaluate(e) {
      // 通过 findIndex 获取下标
      let evaluateIndex = this.model.studentDimensionEvaluationList.findIndex(item => item.dimensionCode == e)
      this.model.studentDimensionEvaluationList.splice(evaluateIndex, 1)
      this.evaluateTemList.splice(evaluateIndex, 1)
    },
    // 评分组件传值获取评价模板
    onStarChange(data) {
      console.log(data);
      let evaluateChild, evaluateTem, title
      switch (data.value) {
        case 1:
          title = '差评'
          break
        case 2:
        case 3:
          title = '中评'
          break
        case 4:
        case 5:
          title = '好评'
          break
      }
      evaluateChild = this.evaluateList.find(item => item.value == data.id)
      evaluateTem = evaluateChild.children.find(item => item.title == title)
      if (!evaluateTem || !evaluateTem.children) {
        evaluateTem = {
          parentId:evaluateChild.key,
          id:evaluateChild.key,
          children:[
            {title:evaluateChild.title + this.notEvaluate,value:evaluateChild.value + "C01D01"},
          ]
        }
      }else{
        // 判断最后一位是否为特殊字符
        var p = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘’；：”“'。，、？]") 
        evaluateTem.children.forEach(item => {
          if (!p.test(item.title.substring(item.title.length - 1,item.title.length))) {
            item.title += "；"
          }
        });
      }
      this.evaluateTemList.push(evaluateTem)
      // 去重并根据key保留最后一个元素
      this.evaluateTemList = this.$skCommon.uniqueLastChild(this.evaluateTemList, 'parentId')
    },
    // 点击评语模板填充评语输入框
    setEvaluationContent(data,index,i) {
      let label = data.title.substring(0,data.title.length - this.notEvaluate.length )
      if (data.title != (label + this.notEvaluate)) {
        if (this.evaluationContentValue.indexOf(data.value) != -1) {
          // let index =  this.evaluationContentArr.findIndex(item=>item == data.title);
          // this.evaluationContentArr.splice(index,1)
          let reg = new RegExp(data.title, 'g') 
          this.model.evaluationContent = this.evaluationContent.replace(reg, '')
          let regValue = new RegExp(data.value, 'g') 
          this.evaluationContentValue = this.evaluationContentValue.replace(regValue, '')
        } else {
          // this.evaluationContentArr.push(data.title)
          this.model.evaluationContent += data.title;
          this.evaluationContentValue += data.value
        }
        // this.model.evaluationContent = this.evaluationContentArr.join("")
      }
    },
    // 判断是否选中评价模板
    selectType(data){
      if (this.evaluationContentValue.indexOf(data.value) != -1) {
        return true
      }else{
        return false;
      }
    },
    getPhotoData(data){
      this.studentPhoto = data;
    },
    onSubmit(){
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.$refs.skUpload.onSubmit();
            let data = [],flag = false;
            if (this.model.studentDimensionEvaluationList.length > 0 && this.studentPhoto.length > 0 ) {
              this.evaluationData.studentId.forEach(item => {
                let json = {
                  studentId:item,
                  evaluationType:this.evaluationData.evaluationType,
                  evaluationContent:this.model.evaluationContent,
                  evaluationCategory:this.evaluationCategory,
                  studentDimensionEvaluationList: this.model.studentDimensionEvaluationList 
                }
                let classItem = this.evaluationData.classId.find(c=>c.stuId == item);
                json.classId = classItem.classId
                let arr = []
                this.studentPhoto.find(el=>{
                  if (el.id == item || el.id == "") {
                    arr.push(el.url)
                  }
                })
                if (arr.length == 0) {
                  flag = true
                }else{
                  flag = false
                  json.photo = arr.join(",")
                  data.push(json)
                }
              });
              if (flag) {
                this.$message.warning("请为幼儿选择照片！");
                return;
              }
              resolve(data);
            }
            if(this.model.studentDimensionEvaluationList.length == 0 && this.studentPhoto.length == 0 ){
              resolve(data);
            }
          }
        })
      })
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */

/* 评价维度模板 */

.type-checkbox-box {
  display: flex;
  flex-wrap: wrap;
}
.type-checkbox-content {
  margin-right: 15px;
  margin-bottom: 15px;
}
.type-label {
  display: block;
  line-height: 33px;
  padding: 0 17px;
  border: 1px solid #dcdfe6;
  border-radius: 38px;
  text-align: center;
  cursor: pointer;
}

.type-label-active{
  border: 1px solid #ffaa44;
  background: #ffaa44;
  color: #fff;
}
</style>
